package org.adorsys.aderp.aderplogin.init;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.adorsys.aderp.aderplogin.service.AderpClientDataService;
import org.adorsys.aderp.aderplogin.service.AderpUserDataService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ServletContextAware;

public class AderpLoginDataLoaderService implements ServletContextAware {
	@Resource
	private AderpClientDataService aderpClientDataService;
	@Resource
	private ClientInitFiles clientInitFiles;
	
	@Resource
	private AderpUserDataService aderpUserDataService;
	@Resource
	private UserInitFiles userInitFiles;
	
	private ServletContext servletContext;
	
	@Transactional
	public void initApplication() {
		
		List<String> clientFiles = clientInitFiles.getInitFiles();
		for (String dataXLS : clientFiles) {
			InputStream inputStream = servletContext.getResourceAsStream(dataXLS);
	        InputStream inputXLS = new BufferedInputStream(inputStream);
	        aderpClientDataService.importDataXLS(inputXLS);

	        try {
				inputXLS.close();
			} catch (IOException e) {
				throw new IllegalStateException(e);
			}
		}
		
		List<String> userFiles = userInitFiles.getInitFiles();
		for (String dataXLS : userFiles) {
			InputStream inputStream = servletContext.getResourceAsStream(dataXLS);
	        InputStream inputXLS = new BufferedInputStream(inputStream);
	        aderpUserDataService.importDataXLS(inputXLS);

	        try {
				inputXLS.close();
			} catch (IOException e) {
				throw new IllegalStateException(e);
			}
		}
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	
}
